package me.fung.rem.app.settings

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import me.fung.keen.app.view.Presenter
import me.fung.rem.bean.repo.configAutoLoginDate
import me.fung.rem.bean.repo.configSearchDays

class SettingsPresenter : Presenter() {

    @OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class)
    val single = newSingleThreadContext("SettingsPresenter")

    @OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class)
    private val receiveDispatcher = newSingleThreadContext("SettingsPresenter")

    private val channel = Channel<() -> Unit>(1, BufferOverflow.DROP_OLDEST) // 启动带缓冲的通道

    suspend fun saveAutoLoginDate(day: Int) {
        channel.send {
            configAutoLoginDate = day
        }
    }

    suspend fun saveSearchDays(day: Int) {
        channel.send {
            configSearchDays = day
        }
    }

    private var job: Job? = null
    fun receiveJob() {
        job = CoroutineScope(receiveDispatcher).launch {
            for (b in channel) {
                b()
            }
        }
    }

    fun cancelJob() {
        job?.cancel()
    }

}